package ru.urfc.portal.ui.client.renderers;

import ru.urfc.portal.ui.client.descriptor.CompositeGridField;
import ru.urfc.portal.ui.client.descriptor.GridField;

import com.extjs.gxt.ui.client.data.ModelData;
import com.google.gwt.dom.client.Element;

public class CoordinatesRenderer extends SimpleRenderer {
	
	private static final int DIVIDER = 100;
	CompositeGridField compositeGridField;
	
	public CoordinatesRenderer(CompositeGridField compositeGridField, Element element) {
		super(compositeGridField, element);
		this.compositeGridField = compositeGridField;
	}

	@Override
	public String render(ModelData modelData) {
		GridField latitudeField = compositeGridField.getGridFields().get(0);
		GridField longitudeField = compositeGridField.getGridFields().get(1);
		Double latitude = latitudeField.getValue(modelData);
		Double longitude = longitudeField.getValue(modelData);
		if (latitude == null || longitude == null) {
			return "";
		}
		return renderOne(latitude, "СШ", "ЮШ") + ", " + renderOne(longitude, "ВД", "ЗД");
	}

	private String renderOne(Double dblValue, String positive, String negative) {
		boolean isPositive = dblValue > 0;
		Double dbl = dblValue * (isPositive? 1: -1) * DIVIDER + 0.5;
		int intValue = dbl.intValue();
		return intValue / DIVIDER + "\u00B0" + intValue % DIVIDER + " " + (isPositive? positive: negative); 
	}
	
}
